﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using EvidenceLib.Base;
using EvidenceLib.Case;
using EvidenceLib.System;
using EvidenceService.Case;
using EvidenceService.Core;
using EvidenceService.System;
using EvidenceWeb.Models;
using EvidenceWeb.Util;
using NHibernate;
using System.Reflection;

namespace EvidenceWeb.Controllers
{
    public class CaseController : Controller
    {
        //
        // GET: /Case/

        public ActionResult Index()
        {
            return View();
        }

        #region 物品记录表

        public ActionResult EvidenceBillListView()
        {

            return View();
        }

        public ActionResult EvidenceBillView()
        {
            return View();
        }

        public ActionResult LoadEvidenceBillSimpleList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                IEnumerable<object> ls = new List<object>();

                try
                {
                    int pageIndex = 0;
                    int.TryParse(Request["page"], out pageIndex);

                    int pageSize = 0;
                    int.TryParse(Request["rows"], out pageSize);

                    string s = Request["evidenceBillQuery"];
                    EvidenceBillQuery query = null;

                    if (s != null)
                        query = JsonSerializerUtil.JsonToEntity<EvidenceBillQuery>(Request["evidenceBillQuery"]);
                    else
                        query = new EvidenceBillQuery();

                    User user = HttpContext.Session["User"] as User;

                    string baseHql = "from EvidenceBill as b   where 1=1 ";

                    RoleService roleSvr = new RoleService(session);

                    if (!roleSvr.IsPermission(user.Id, "queryer"))
                    {
                        if (roleSvr.IsPermission(user.Id, "deptqueryer"))
                        {
                            baseHql += string.Format(" and (b.ManageDept.Id= {0} or b.TransferDept.Id={0} )", user.Department.Id);
                        }
                        else
                        {
                            baseHql += string.Format(" and (b.Preparer.Id= {0} or b.Checker.Id={1} )", user.Id, user.Id);
                        }
                    }
                    string hql = null;
                    string totalHql = null;

                    if (query.TargetBillType > 0)
                    {
                        baseHql += " and b.ManageDept.Id = " + user.Department.Id;
                    }

                    switch (query.TargetBillType)
                    {
                        case 0:
                            baseHql += "";
                            break;
                        case 2://入库单
                            baseHql += " and b.IsCheck=true and b.IsFinish =false and exists (from Evidence as e where b.Id=e.BillId and e.Qty>(e.StockQty + e.OutStockQty + e.InquiryOutStockQty))";
                            break;
                        //case 3://调用入库
                        //    baseHql += " and b.IsCheck=true and b.IsFinish =false and b.StockState in(0,1) and exists( from  Evidence as ev where ev.BillId=b.Id and ev.InquiryOutStockQty > 0)";
                        //    break;
                        case 4://出库
                        case 5://调用出库
                            baseHql += " and b.IsCheck=true and b.IsFinish =false and exists (from Evidence as e where b.Id=e.BillId and e.StockQty > 0)";
                            break;
                    }
                    switch (query.StockState)
                    {
                        case -1: //全部未结案
                            baseHql += " and b.IsFinish=false";
                            break;
                        case -2: //未审核
                            baseHql += " and b.IsCheck=false";
                            break;
                        case -4://已审核,未入库
                            baseHql += " and b.IsCheck=true and b.StockState=0";
                            break;
                        case 1://部分入库
                            baseHql += " and  b.StockState=1";
                            break;
                        case 2://全部入库
                            baseHql += " and  b.StockState=2";
                            break;
                        case 32://全部入库
                            baseHql += " and  b.StockState=32";
                            break;
                        case -8://全部入库
                            baseHql += " and  b.IsFinish=true";
                            break;
                    }

                    if (!string.IsNullOrEmpty(query.Number))
                        baseHql += string.Format(" and b.Number like '%{0}%'", query.Number);
                    if (!string.IsNullOrEmpty(query.SerialNo))
                        baseHql += string.Format(" and b.SerialNo like '%{0}%'", query.SerialNo);
                    if (query.DeptId > 0)
                        baseHql += " and b.TransferDept.Id=" + query.DeptId;
                    if (query.BeginTime != null)
                        baseHql += string.Format(" and b.BillTime >='{0}'", query.BeginTime.Value);
                    if (query.EndTime != null)
                        baseHql += string.Format(" and b.BillTime <='{0}'", query.EndTime.Value.AddDays(1));
                    if (!string.IsNullOrEmpty(query.TransferName))
                        baseHql += string.Format(" and b.TransferName Like '%{0}%'", query.TransferName);
                    if (!string.IsNullOrEmpty(query.EvidenceName))
                        baseHql += string.Format(" and exists(from Evidence as d where d.BillId=b.Id and d.Name Like '%{0}%')", query.EvidenceName);

                    EvidenceBillService svr = new EvidenceBillService(session);

                    //baseHql += " order by b.BillTime desc";

                    totalHql = "select count(b) " + baseHql;
                    hql = "select b " + baseHql + " order by b.BillTime desc";
                    Tuple<IList<EvidenceBill>, int> result = svr.LoadListByHQLWithPaging(hql, totalHql, pageSize, pageIndex);

                    ls = (from b in result.Item1
                          select new
                              {
                                  Id = b.Id,
                                  IsCheck = b.IsCheck,
                                  IsFinish = b.IsFinish,
                                  StockState = b.StockState,
                                  Number = b.Number,
                                  SerialNo = b.SerialNo,
                                  BillTime = b.BillTime,
                                  TransferDeptName = b.TransferDept == null ? null : b.TransferDept.Name.EndsWith("青羊区分局") ? b.TransferDept.Name : b.TransferDept.Name.Replace("青羊区分局", ""),
                                  TransferName = b.TransferName,
                                  ManageDeptName = b.ManageDept == null ? null : b.ManageDept.Name.EndsWith("青羊区分局") ? b.ManageDept.Name : b.ManageDept.Name.Replace("青羊区分局", "")
                              });
                    return Json(new { total = result.Item2, rows = ls });
                }
                catch (Exception ex)
                {
                    return Json(new { total = 0, rows = ls });
                }

            }
        }

        /// <summary>
        /// 读取单据信息
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadEvidenceBill()
        {

            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    EvidenceBillService svr = new EvidenceBillService(session);
                    EvidenceService.Case.EvidenceService eSvr = new EvidenceService.Case.EvidenceService(session);

                    int id = 0;
                    int.TryParse(Request["evidenceBillId"], out id);


                    EvidenceBill bill = svr.LoadById(id);
                    IList<Evidence> ls = eSvr.LoadByHQL("from Evidence as e where e.BillId= " + id);

                    string json = JsonSerializerUtil.EntityToJson(bill);
                    string detailJson = JsonSerializerUtil.EntityToJson(ls);

                    if (bill.Id > 0)
                    {
                        return Json(new { IsSuccess = true, Bill = json, Details = detailJson });
                    }
                    else
                    {
                        return Json(new { IsSuccess = false });
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }
        /// <summary>
        /// 保存物品记录单据
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveEvidenceBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                User user = Session["User"] as User;

                RoleService roleSvr = new RoleService(session);


                ITransaction tx = session.BeginTransaction();
                try
                {
                    EvidenceBillService svr = new EvidenceBillService(session);

                    EvidenceService.Case.EvidenceService eSvr = new EvidenceService.Case.EvidenceService(session);

                    string data = Request["evidenceBillJson"];

                    string detailData = Request["detailsJson"];

                    EvidenceBill bill = JsonSerializerUtil.JsonToEntity<EvidenceBill>(data);
                    IList<Evidence> ls = JsonSerializerUtil.JsonToEntities<Evidence>(detailData);


                    svr.SaveOrUpdate(bill);

                    foreach (Evidence evidence in ls)
                    {
                        evidence.BillId = bill.Id;

                        eSvr.SaveOrUpdate(evidence);
                    }

                    tx.Commit();

                    return Json(new { IsSuccess = true, Data = bill.Id });
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        /// <summary>
        /// 删除物品记录单据
        /// </summary>
        /// <returns></returns>
        public ActionResult DeleteEvidenceBill()
        {

            using (ISession session = HbmSessionFactory.GetSession())
            {
                User user = Session["User"] as User;

                EvidenceBillService svr = new EvidenceBillService(session);
                int id = Convert.ToInt32(Request["Id"]);

                EvidenceBill bill = session.Load<EvidenceBill>(id);

                if (bill == null)
                {
                    return Json(new { IsSuccess = false, Data = "单据不存在!" });
                }

                RoleService roleSvr = new RoleService(session);

                if (!roleSvr.IsPermission(user.Id, "stockmgr") && bill.Preparer.Id != user.Id)
                {
                    return Json(new { IsSuccess = false, Data = "单据只能由录入人员删除!" });
                }

                session.Clear();

                ITransaction tx = session.BeginTransaction();
                try
                {

                    string hql = string.Format(" delete from  EvidenceBill where Id ={0}", id);
                    svr.DeletebyHQL(hql);
                    tx.Commit();

                    return Json(new { IsSuccess = true });
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }

            }
        }

        /// <summary>
        /// 审核物品单
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckEvidenceBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                int checkDeptId = int.Parse(Request["checkDeptId"]);

                int checkerId = int.Parse(Request["checkerId"]);

                int billId = int.Parse(Request["billId"]);

                User user = Session["User"] as User;

                EvidenceBill bill = session.Load<EvidenceBill>(billId);


                if (bill == null)
                {
                    return Json(new { IsSuccess = false, Data = "要审核的单据不存在!" });
                }

                session.Clear();

                ITransaction tx = session.BeginTransaction();
                try
                {
                    EvidenceBillService svr = new EvidenceBillService(session);

                    svr.CheckBill(billId, checkDeptId, checkerId);

                    tx.Commit();

                    return Json(new { IsSuccess = true });
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        public ActionResult LoadOutStorages()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                return null;
            }
        }

        /// <summary>
        /// 读取物品明细
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadEvidenceListByBillId()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                EvidenceService.Case.EvidenceService svr = new EvidenceService.Case.EvidenceService(session);

                int id = 0;
                int.TryParse(Request["evidenveBillId"], out id);

                IList<Evidence> details = svr.LoadByHQL("from EvidenceDetail as d where d.Bill.Id=" + id);
                string json = JsonSerializerUtil.EntityToJson(details);

                return Json(new { IsSuccess = true, Data = json });
            }
        }


        public ActionResult EvidenceView()
        {
            return View();
        }
        /// <summary>
        /// 通过Id读取单个Evidence 
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadEvidence()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                EvidenceService.Case.EvidenceService svr = new EvidenceService.Case.EvidenceService(session);

                int id = 0;
                int.TryParse(Request["evidenceId"], out id);

                Evidence ev = svr.LoadById(id);
                string json = JsonSerializerUtil.EntityToJson(ev);

                return Json(new { IsSuccess = true, Data = json });
            }
        }

        public ActionResult LoadEvidenceList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    EvidenceService.Case.EvidenceService svr = new EvidenceService.Case.EvidenceService(session);

                    string data = Request["evidenceQuery"];

                    EvidenceQuery query = JsonSerializerUtil.JsonToEntity<EvidenceQuery>(data);

                    IList<Evidence> evs = svr.LoadByHQL("from Evidence as e where e.BillId=" + query.BillId).ToList<Evidence>();

                    string json = JsonSerializerUtil.EntityToJson(evs);

                    return Json(new { IsSuccess = true, total = evs.Count(), rows = evs });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        /// <summary>
        /// 保存Evidence
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveEvidence()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    string data = Request["evidenceJson"];

                    Evidence ev = JsonSerializerUtil.JsonToEntity<Evidence>(data);

                    EvidenceService.Case.EvidenceService svr = new EvidenceService.Case.EvidenceService(session);

                    svr.SaveOrUpdate(ev);

                    return Json(new { IsSuccess = true, Data = ev.Id });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }


        /// <summary>
        /// 物品记录单到入库申请单
        /// </summary>
        /// <param name="sourceId"></param>
        /// <returns></returns>
        private ActionResult EvidenceToInRequestBill(int sourceId)
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                //ITransaction tx = session.BeginTransaction();
                try
                {
                    EvidenceBillService evidBillSvr = new EvidenceBillService(session);

                    EvidenceService.Case.EvidenceService evidSvr = new EvidenceService.Case.EvidenceService(session);

                    EvidenceBill evidBill = evidBillSvr.LoadById(sourceId);

                    IList<Evidence> evids = evidSvr.LoadByHQL("from Evidence as e where e.BillId=" + sourceId);

                    StockBill stockBill = new StockBill();
                    stockBill.BillTime = DateTime.Now;
                    stockBill.BillType = BillTypeEnum.InStock;
                    stockBill.Department = evidBill.Department;
                    stockBill.Description = evidBill.Description;
                    stockBill.Number = evidBill.Number;
                    stockBill.Preparer = Session["User"] as User;
                    stockBill.SourceBillId = sourceId;
                    stockBill.SourceBillType = BillTypeEnum.EvidenceBill;
                    stockBill.TransferDept = evidBill.TransferDept;
                    //stockBill.Transfer = evidBill.Transfer;

                    //StockBillService stockSvr = new StockBillService(session);
                    //StockBillDetailService stockDetailSvr = new StockBillDetailService(session);

                    //stockSvr.SaveOrUpdate(stockBill);

                    IList<StockBillDetail> details = new List<StockBillDetail>();

                    foreach (Evidence evid in evids)
                    {
                        StockBillDetail detail = new StockBillDetail();
                        detail.Amount = evid.Amount;
                        detail.Evidence = evid;
                        detail.Qty = evid.Qty;
                        detail.Storage = null;

                        details.Add(detail);

                    }

                    string billJson = JsonSerializerUtil.EntityToJson(stockBill);
                    string detailsJson = JsonSerializerUtil.EntityToJson(details);

                    return Json(new { IsSuccess = true, BillJson = billJson, DetailsJson = detailsJson });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        #endregion



        #region 附件管理

        public ActionResult CaseFileListView()
        {
            return View();
        }

        #endregion

        #region  库存单据

        public ActionResult StockBillListView()
        {
            return View();
        }

        public ActionResult StockBillView()
        {
            return View();
        }

        public ActionResult LoadStockBillSimpleList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {

                int pageIndex = 0;
                int.TryParse(Request["page"], out pageIndex);

                int pageSize = 0;
                int.TryParse(Request["rows"], out pageSize);

                string s = Request["stockBillList_Query"];
                StockBillQuery query = null;

                User user = Session["User"] as User;

                if (!string.IsNullOrEmpty(s))
                    query = JsonSerializerUtil.JsonToEntity<StockBillQuery>(s);
                else
                    query = new StockBillQuery();

                return LoadStockBillSimpleList(session, pageIndex, pageSize, query, user);
            }
        }

        public ActionResult LoadStockBillSimpleListForEvidenceBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                int pageIndex = 0;
                int.TryParse(Request["page"], out pageIndex);

                int pageSize = 0;
                int.TryParse(Request["rows"], out pageSize);

                string s = Request["stockBillList_Query"];
                StockBillQuery query = null;

                User user = Session["User"] as User;

                if (!string.IsNullOrEmpty(s))
                    query = JsonSerializerUtil.JsonToEntity<StockBillQuery>(s);
                else
                    query = new StockBillQuery();

                if (query.CaseId == 0)
                {
                    return Json(new { total = 0, rows = new List<object>() });
                }
                else
                {
                    return LoadStockBillSimpleList(session, pageIndex, pageSize, query, user);
                }
            }
        }

        private ActionResult LoadStockBillSimpleList(ISession session, int pageIndex, int pageSize, StockBillQuery query, User user)
        {
            try
            {

                string baseHql = " from StockBill as s";

                if (query.BillType == -1)
                    baseHql += " where 1=1 ";
                else
                    baseHql += " where s.BillType = " + query.BillType;
                string hql = null;
                string totalHql = null;

                RoleService roleSvr = new RoleService(session);

                if (query.TargetBillType > 0)
                {
                    baseHql += " and s.ManageDept.Id =" + user.Department.Id;
                }
                else if (!roleSvr.IsPermission(user.Id, "queryer"))
                { 
                    baseHql += string.Format(" and (s.Department.Id = {0} or s.ManageDept.Id={1})", user.Department.Id, user.Department.Id);
                }

                if (!string.IsNullOrEmpty(query.Number))
                    baseHql += string.Format(" and s.Number like '%{0}%'", query.Number);
                if (!string.IsNullOrEmpty(query.SerialNo))
                    baseHql += string.Format(" and s.SerialNo like '%{0}%'", query.SerialNo);
                if (query.CaseId > 0)
                    baseHql += " and s.CaseId =" + query.CaseId;
                if (query.TargetBillType == 3)
                    baseHql += " and s.BillType = 5 and s.IsCheck = true and exists(from StockBillDetail as sd where s.Id=sd.BillId and sd.VerificationQty < sd.Qty)";
                if (query.CheckState == 1)
                    baseHql += " and s.IsCheck = true";
                else if (query.CheckState == 0)
                    baseHql += " and s.IsCheck = false";
                if (!string.IsNullOrEmpty(query.Confirmer))
                    baseHql += " and s.CheckerName.Name Like '%" + query.CheckerName + "%'";
                if (query.DeptId > 0)
                    baseHql += " and s.TransferDept.Id=" + query.DeptId;
                if (query.BeginTime != null)
                    baseHql += string.Format(" and s.BillTime >='{0}'", query.BeginTime.Value);
                if (query.EndTime != null)
                    baseHql += string.Format(" and s.EndTime <='{0}'", query.EndTime.Value.AddDays(1));
                if (!string.IsNullOrEmpty(query.TransferName))
                    baseHql += string.Format(" and s.TransferName Like '%{0}%'", query.TransferName);
                if (!string.IsNullOrEmpty(query.EvidenceName))
                    baseHql += string.Format(" and exists(from StockBillDetail as d where d.BillId=s.Id and d.Evidence.Name Like '%{0}%')", query.EvidenceName);

                StockBillService svr = new StockBillService(session);

                totalHql = "select count(s) " + baseHql;
                hql = "select s " + baseHql + " order by s.BillTime Desc";

                Tuple<IList<StockBill>, int> result = svr.LoadListByHQLWithPaging(hql, totalHql, pageSize, pageIndex);

                var ls = (from b in result.Item1
                          select new
                          {
                              BillType = b.BillType,
                              Id = b.Id,
                              IsCheck = b.IsCheck,
                              Number = b.Number,
                              SerialNo = b.SerialNo,
                              BillTime = b.BillTime,
                              TransferDeptId = b.TransferDept == null ? "" : b.TransferDept.Id.ToString(),
                              TransferDeptName = b.TransferDept == null ? null : b.TransferDept.Name,
                              TransferName = b.TransferName,
                              ManageDeptName = b.ManageDept == null ? null : b.ManageDept.Name
                          });
                return Json(new { total = result.Item2, rows = ls });
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Data = ex.Message, total = 0, rows = new List<object>() });
            }
        }

        /// <summary>
        /// 读取出入库单据
        /// </summary>
        /// <returns></returns>
        public ActionResult LoadStockBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    StockBillService svr = new StockBillService(session);
                    StockBillDetailService eSvr = new StockBillDetailService(session);

                    int id = 0;
                    int.TryParse(Request["stockBillId"], out id);


                    StockBill bill = svr.LoadById(id);
                    IList<StockBillDetail> ls = eSvr.LoadByHQL("from StockBillDetail as e where e.BillId= " + id);

                    string json = JsonSerializerUtil.EntityToJson(bill);
                    string detailJson = JsonSerializerUtil.EntityToJson(ls);

                    if (bill.Id > 0)
                    {
                        return Json(new { IsSuccess = true, Bill = json, Details = detailJson });
                    }
                    else
                    {
                        return Json(new { IsSuccess = false });
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        /// <summary>
        /// 保存出入库单据
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveStockBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                RoleService roleSvr = new RoleService(session);

                User user = Session["User"] as User;

                bool isPermit = roleSvr.IsPermission(user.Id, "stocker");

                if (isPermit)
                {
                    ITransaction tx = session.BeginTransaction();
                    try
                    {
                        StockBillService stockBillSvr = new StockBillService(session);
                        StockBillDetailService stockBillDetailSvr = new StockBillDetailService(session);

                        string data = Request["stockBillJson"];
                        string detailData = Request["detailsJson"];

                        StockBill bill = JsonSerializerUtil.JsonToEntity<StockBill>(data);
                        IList<StockBillDetail> ls = JsonSerializerUtil.JsonToEntities<StockBillDetail>(detailData);

                        stockBillSvr.SaveOrUpdate(bill);

                        foreach (StockBillDetail detail in ls)
                        {
                            detail.BillId = bill.Id;
                            stockBillDetailSvr.SaveOrUpdate(detail);
                        }

                        EvidenceBillService ebSvr = new EvidenceBillService(session);
                        //ebSvr.ModfiyStockState(bill.SourceBillId);

                        tx.Commit();

                        return Json(new { IsSuccess = true, Data = bill.Id });
                    }
                    catch (Exception ex)
                    {
                        if (tx.IsActive)
                            tx.Rollback();

                        return Json(new { IsSuccess = false, Data = ex.Message });
                    }
                }
                else
                {
                    return Json(new { IsSuccess = false, Data = "没有操作权限，如需操作请联系管理员" });
                }
            }
        }


        public ActionResult CheckStockBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                User user = HttpContext.Session["User"] as User;

                RoleService roleSvr = new RoleService(session);

                int checkerId = int.Parse(Request["checkerId"]);

                int billId = int.Parse(Request["billId"]);

                int checkDeptId = int.Parse(Request["checkDeptId"]);


                ITransaction tx = session.BeginTransaction();
                try
                {
                    StockBill bill = session.Load<StockBill>(billId);

                    StockBillService svr = new StockBillService(session);

                    if (bill.Department.Id != user.Department.Id)
                    {
                        return Json(new { IsSuccess = false, Data = "该单据不在您所属部门，不能审核" });
                    }
                    session.Clear();
                    svr.CheckBill(billId, checkDeptId, checkerId, tx);


                    tx.Commit();

                    return Json(new { IsSuccess = true });
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }

            }
        }

        public ActionResult DeleteStockBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                User user = HttpContext.Session["User"] as User;

                int billId = int.Parse(Request["billId"]);

                int checkDeptId = int.Parse(Request["checkDeptId"]);

                StockBill bill = session.Load<StockBill>(billId);

                if (bill == null)
                {
                    return Json(new { IsSuccess = false, Data = "该单据不存在!" });
                }

                if (bill.IsCheck)
                {
                    return Json(new { IsSuccess = false, Data = "已经审核的单据不能删除!" });
                }

                if (bill.Preparer.Id != user.Id)
                {
                    return Json(new { IsSuccess = false, Data = "只能由单据记录人删除!" });
                }

                session.Clear();

                ITransaction tx = session.BeginTransaction();
                try
                {
                    StockBillService svr = new StockBillService(session);


                    svr.DeletebyHQL(string.Format(" delete from  StockBill where Id ={0}", billId));

                    tx.Commit();

                    return Json(new { IsSuccess = true });
                }
                catch (Exception ex)
                {
                    if (tx.IsActive)
                        tx.Rollback();

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        public ActionResult StockDetailView()
        {
            return View();
        }

        #endregion

        #region 结案
        public ActionResult CloseCaseListView()
        {
            return View();
        }

        public ActionResult LoadCloseEvidenceSimpleList()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                IEnumerable<object> ls = new List<object>();

                try
                {
                    int pageIndex = 0;
                    int.TryParse(Request["page"], out pageIndex);

                    int pageSize = 0;
                    int.TryParse(Request["rows"], out pageSize);

                    string s = Request["closeEvidenceQuery"];
                    CloseEvidenceList_Query query = null;

                    if (s != null)
                        query = JsonSerializerUtil.JsonToEntity<CloseEvidenceList_Query>(Request["closeEvidenceQuery"]);
                    else
                        query = new CloseEvidenceList_Query();

                    string baseHql = "from EvidenceBill as b   where 1=1 ";
                    string hql = null;
                    string totalHql = null;

                    if (query.State == 0)
                        baseHql += " and  b.IsCheck =true";
                    if (query.State == 0)
                        baseHql += " and b.StockState =32 and b.IsFinish =false";
                    if (query.State == 1)
                        baseHql += " and b.IsFinish=true";

                    if (query.DeptId > 0)
                        baseHql += " and b.TransferDept.Id=" + query.DeptId;
                    if (!string.IsNullOrEmpty(query.CaseNo))
                        baseHql += string.Format(" and b.Number Like '%{0}%'", query.CaseNo);
                    if (!string.IsNullOrEmpty(query.EvidenceName))
                        baseHql += string.Format(" and exists(from Evidence as d where d.BillId=b.Id and d.Name Like '%{0}%')", query.EvidenceName);

                    EvidenceBillService svr = new EvidenceBillService(session);

                    totalHql = "select count(b) " + baseHql;
                    hql = "select b " + baseHql + " order by b.BillTime desc";
                    Tuple<IList<EvidenceBill>, int> result = svr.LoadListByHQLWithPaging(hql, totalHql, pageSize, pageIndex);

                    ls = (from b in result.Item1
                          select new
                          {
                              Id = b.Id,
                              IsCheck = b.IsCheck,
                              IsFinish = b.IsFinish,
                              StockState = b.StockState,
                              Number = b.Number,
                              BillTime = b.BillTime,
                              TransferDeptName = b.TransferDept == null ? null : b.TransferDept.Name.Replace("青羊区分局", ""),
                              TransferName = b.TransferName,
                              ManageDeptName = b.ManageDept == null ? null : b.ManageDept.Name.Replace("青羊区分局", "")
                          });
                    return Json(new { total = result.Item2, rows = ls });
                }
                catch (Exception ex)
                {
                    return Json(new { total = 0, rows = ls });
                }
            }
        }

        public ActionResult CloseEvidenceBill()
        {
            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    int billId = int.Parse(Request["billId"]);

                    EvidenceBillService svr = new EvidenceBillService(session);

                    RoleService roleServer = new RoleService(session);

                    if (svr.CheckCloseBill(billId))
                    {
                        svr.CloseBill(billId);
                        return Json(new { IsSuccess = true });
                    }
                    else
                    {
                        return Json(new { IsSuccess = false, Data = "物品单未完全出库，不能结案!" });
                    }
                }
                catch (Exception ex)
                {

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
            }
        }

        #endregion



        #region 获取单据编号

        public ActionResult LoadNextBillSerialNo()
        {
            int billType = int.Parse(Request["billType"]);

            using (ISession session = HbmSessionFactory.GetSession())
            {
                try
                {
                    BillSerialNoService svr = new BillSerialNoService(session);

                    string result = svr.GetNextSerialNo((BillTypeEnum)billType);

                    return Json(new { IsSuccess = true, Data = result });
                }
                catch (Exception ex)
                {
                    return Json(new { IsSuccess = false, Data = ex.Message });
                }

            }
        }

        #endregion


        public ActionResult LoadBillBySerialNo()
        {
            string serialNo = Request["serialNo"];

            using (ISession session = HbmSessionFactory.GetSession())
            {
                IDataReader reader = null;

                try
                {
                    string sql = "select id as CaseId,id as BillId,1 as BillType,serialNo,ManageDeptId from Ev_EvidenceBill where serialNo=@serialNo union select CaseId, id as BillId,billType,SerialNo,ManageDeptId from Ev_stockBill where serialNo=@serialNo";

                    IDbCommand cmd = session.Connection.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;

                    IDbDataParameter p1 = cmd.CreateParameter();
                    p1.ParameterName = "@serialNo";
                    p1.DbType = DbType.String;
                    p1.Value = serialNo;
                    p1.Size = 100;

                    cmd.Parameters.Add(p1);

                    reader = cmd.ExecuteReader();

                    var result = new object();

                    while (reader.Read())
                    {
                        result = new { CaseId = Convert.ToInt32(reader["CaseId"]), BillId = Convert.ToInt32(reader["BillId"]), BillType = Convert.ToInt32(reader["BillType"]), SerialNo = Convert.ToString(reader["SerialNo"]), ManageDeptId = Convert.ToInt32(reader["ManageDeptId"]) };
                    }

                    return Json(new { IsSuccess = true, Data = result });
                }
                catch (Exception ex)
                {

                    return Json(new { IsSuccess = false, Data = ex.Message });
                }
                finally
                {
                    if (reader != null && !reader.IsClosed)
                    {
                        reader.Close();
                    }
                }

            }
        }
    }

}
